import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Card, Table, Button, Input, Space, Tag, message, Modal, Form, Tree, Switch } from 'antd'
import { PlusOutlined, SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined, SafetyOutlined, CrownOutlined, UserOutlined, ToolOutlined } from '@ant-design/icons'
import { fetchRoleList, fetchRoleById, addRole, modifyRole, removeRole, assignRolePermissions } from '@/store/slices/roleSlice'
import { fetchPermissionList } from '@/store/slices/permissionSlice'
import './index.scss'

const PermissionManagement = () => {
  const dispatch = useDispatch()
  const { roleList, loading } = useSelector((state) => state.role)
  const { permissionList } = useSelector((state) => state.permission)
  
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingRole, setEditingRole] = useState(null)
  const [form] = Form.useForm()
  
  // 搜索表单状态
  const [searchForm, setSearchForm] = useState({
    roleName: '',
    status: 'all'
  })

  // 加载角色和权限列表
  useEffect(() => {
    dispatch(fetchRoleList())
    dispatch(fetchPermissionList())
  }, [dispatch])

  // 权限树数据
  const permissionTree = [
    {
      title: '仪表盘',
      key: 'dashboard',
      children: [
        { title: '查看仪表盘', key: 'dashboard:view' },
      ]
    },
    {
      title: '阅读管理',
      key: 'reading',
      children: [
        { title: '图书管理', key: 'reading:books', children: [
          { title: '查看图书', key: 'reading:books:view' },
          { title: '新增图书', key: 'reading:books:create' },
          { title: '编辑图书', key: 'reading:books:edit' },
          { title: '删除图书', key: 'reading:books:delete' },
        ]},
        { title: '分类管理', key: 'reading:categories', children: [
          { title: '查看分类', key: 'reading:categories:view' },
          { title: '新增分类', key: 'reading:categories:create' },
          { title: '编辑分类', key: 'reading:categories:edit' },
          { title: '删除分类', key: 'reading:categories:delete' },
        ]},
        { title: '阅读记录', key: 'reading:records', children: [
          { title: '查看记录', key: 'reading:records:view' },
          { title: '导出记录', key: 'reading:records:export' },
        ]},
        { title: '阅读进度', key: 'reading:progress', children: [
          { title: '查看进度', key: 'reading:progress:view' },
          { title: '导出进度', key: 'reading:progress:export' },
        ]},
      ]
    },
    {
      title: '读者管理',
      key: 'readers',
      children: [
        { title: '读者列表', key: 'readers:list', children: [
          { title: '查看读者', key: 'readers:list:view' },
          { title: '新增读者', key: 'readers:list:create' },
          { title: '编辑读者', key: 'readers:list:edit' },
          { title: '删除读者', key: 'readers:list:delete' },
        ]},
        { title: '读者分组', key: 'readers:groups', children: [
          { title: '查看分组', key: 'readers:groups:view' },
          { title: '新增分组', key: 'readers:groups:create' },
          { title: '编辑分组', key: 'readers:groups:edit' },
          { title: '删除分组', key: 'readers:groups:delete' },
        ]},
      ]
    },
    {
      title: '用户管理',
      key: 'users',
      children: [
        { title: '用户列表', key: 'users:list', children: [
          { title: '查看用户', key: 'users:list:view' },
          { title: '新增用户', key: 'users:list:create' },
          { title: '编辑用户', key: 'users:list:edit' },
          { title: '删除用户', key: 'users:list:delete' },
        ]},
        { title: '权限管理', key: 'users:permissions', children: [
          { title: '查看权限', key: 'users:permissions:view' },
          { title: '编辑权限', key: 'users:permissions:edit' },
        ]},
      ]
    },
    {
      title: '数据分析',
      key: 'analytics',
      children: [
        { title: '阅读统计', key: 'analytics:reading', children: [
          { title: '查看统计', key: 'analytics:reading:view' },
          { title: '导出数据', key: 'analytics:reading:export' },
        ]},
        { title: '用户行为', key: 'analytics:behavior', children: [
          { title: '查看行为', key: 'analytics:behavior:view' },
          { title: '导出数据', key: 'analytics:behavior:export' },
        ]},
      ]
    },
  ]

  // 模拟数据
  const mockData = [
    {
      key: '1',
      roleId: 4001,
      roleName: '超级管理员',
      roleIcon: <CrownOutlined />,
      roleColor: '#faad14',
      description: '拥有系统所有权限',
      userCount: 2,
      permissions: ['dashboard:view', 'reading:books:view', 'reading:books:create', 'reading:books:edit', 'reading:books:delete'],
      status: '启用',
      createTime: '2021-01-15 10:30'
    },
    {
      key: '2',
      roleId: 4002,
      roleName: '内容管理员',
      roleIcon: <ToolOutlined />,
      roleColor: '#1890ff',
      description: '管理图书和分类',
      userCount: 5,
      permissions: ['dashboard:view', 'reading:books:view', 'reading:books:create', 'reading:books:edit'],
      status: '启用',
      createTime: '2021-01-15 10:35'
    },
    {
      key: '3',
      roleId: 4003,
      roleName: '数据分析员',
      roleIcon: <SafetyOutlined />,
      roleColor: '#52c41a',
      description: '查看和分析数据',
      userCount: 3,
      permissions: ['dashboard:view', 'analytics:reading:view', 'analytics:behavior:view'],
      status: '启用',
      createTime: '2021-02-20 14:20'
    },
    {
      key: '4',
      roleId: 4004,
      roleName: '客服人员',
      roleIcon: <UserOutlined />,
      roleColor: '#722ed1',
      description: '处理读者相关事务',
      userCount: 8,
      permissions: ['dashboard:view', 'readers:list:view', 'readers:list:edit'],
      status: '启用',
      createTime: '2021-03-10 09:15'
    },
  ]

  // 表格列配置
  const columns = [
    {
      title: '角色ID',
      dataIndex: 'roleId',
      key: 'roleId',
      width: 100,
      align: 'center'
    },
    {
      title: '角色信息',
      key: 'roleInfo',
      width: 250,
      render: (_, record) => (
        <div className="role-info-cell">
          <div className="role-icon" style={{ background: record.roleColor }}>
            {record.roleIcon}
          </div>
          <div className="role-details">
            <div className="role-name">{record.roleName}</div>
            <div className="role-desc">{record.description}</div>
          </div>
        </div>
      )
    },
    {
      title: '用户数量',
      dataIndex: 'userCount',
      key: 'userCount',
      width: 120,
      align: 'center',
      render: (count) => (
        <span className="user-count">{count}</span>
      )
    },
    {
      title: '权限数量',
      key: 'permissionCount',
      width: 120,
      align: 'center',
      render: (_, record) => (
        <Tag color="blue">{record.permissions.length} 项</Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text, record) => (
        <Switch 
          checked={text === '启用'} 
          checkedChildren="启用" 
          unCheckedChildren="禁用"
          onChange={(checked) => handleStatusChange(record, checked)}
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      )
    }
  ]

  // 搜索
  const handleSearch = () => {
    dispatch(fetchRoleList())
    message.success('搜索成功')
  }

  // 重置
  const handleReset = () => {
    setSearchForm({
      roleName: '',
      status: 'all'
    })
    message.info('已重置搜索条件')
  }

  // 新建角色
  const handleCreate = () => {
    setEditingRole(null)
    form.resetFields()
    setIsModalVisible(true)
  }

  // 编辑角色
  const handleEdit = async (record) => {
    setEditingRole(record)
    // 获取完整的角色信息（包含权限）
    try {
      const result = await dispatch(fetchRoleById(record.roleId || record.id)).unwrap()
      form.setFieldsValue({
        roleName: result.roleName || result.name,
        description: result.description,
        permissions: result.permissions || [],
        status: result.status
      })
      setIsModalVisible(true)
    } catch (error) {
      message.error('获取角色信息失败')
    }
  }

  // 删除角色
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除角色"${record.roleName}"吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await dispatch(removeRole(record.roleId || record.id)).unwrap()
          message.success('删除成功')
          dispatch(fetchRoleList())
        } catch (error) {
          message.error(error?.message || '删除失败')
        }
      }
    })
  }

  // 状态切换
  const handleStatusChange = (record, checked) => {
    message.success(`已${checked ? '启用' : '禁用'}角色"${record.roleName}"`)
  }

  /**
   * 保存角色信息
   * 验证表单并提交数据
   */
  const handleSave = () => {
    form.validateFields().then(async (values) => {
      try {
        if (editingRole) {
          // 更新角色
          await dispatch(modifyRole({ 
            id: editingRole.roleId || editingRole.id, 
            data: values 
          })).unwrap()
          // 如果有权限修改，也更新权限
          if (values.permissions) {
            await dispatch(assignRolePermissions({
              id: editingRole.roleId || editingRole.id,
              permissionIds: values.permissions
            })).unwrap()
          }
          message.success('修改成功')
        } else {
          // 创建角色
          const result = await dispatch(addRole(values)).unwrap()
          // 如果有权限，分配权限
          if (values.permissions && result.id) {
            await dispatch(assignRolePermissions({
              id: result.id,
              permissionIds: values.permissions
            })).unwrap()
          }
          message.success('创建成功')
        }
        setIsModalVisible(false)
        dispatch(fetchRoleList())
      } catch (error) {
        message.error(error?.message || (editingRole ? '修改失败' : '创建失败'))
      }
    })
  }

  // 使用后端数据或模拟数据
  const actualDataSource = roleList.length > 0 ? roleList : mockData

  // 行选择
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys) => {
      setSelectedRowKeys(selectedKeys)
    }
  }

  return (
    <div className="permission-management-container">
      {/* 搜索表格 */}
      <Card className="search-card" title="查询表格">
        <div className="search-form">
          <div className="form-row">
            <div className="form-item">
              <label>角色名称</label>
              <Input
                placeholder="请输入角色名称"
                value={searchForm.roleName}
                onChange={(e) => setSearchForm({ ...searchForm, roleName: e.target.value })}
              />
            </div>
            <div className="form-item">
              <label>状态</label>
              <Input
                placeholder="全部"
                value={searchForm.status === 'all' ? '全部' : searchForm.status}
                disabled
              />
            </div>
            <div className="form-item form-actions">
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </div>
          </div>
        </div>
      </Card>

      {/* 统计卡片 */}
      <div className="stats-cards">
        <Card className="stat-card">
          <div className="stat-content">
            <div className="stat-info">
              <div className="stat-label">总角色数</div>
              <div className="stat-value">8</div>
            </div>
            <div className="stat-icon total">
              <SafetyOutlined />
            </div>
          </div>
        </Card>
        <Card className="stat-card">
          <div className="stat-content">
            <div className="stat-info">
              <div className="stat-label">管理员数</div>
              <div className="stat-value">18</div>
            </div>
            <div className="stat-icon users">
              <UserOutlined />
            </div>
          </div>
        </Card>
        <Card className="stat-card">
          <div className="stat-content">
            <div className="stat-info">
              <div className="stat-label">权限项数</div>
              <div className="stat-value">45</div>
            </div>
            <div className="stat-icon permissions">
              <ToolOutlined />
            </div>
          </div>
        </Card>
        <Card className="stat-card">
          <div className="stat-content">
            <div className="stat-info">
              <div className="stat-label">启用角色</div>
              <div className="stat-value">6</div>
            </div>
            <div className="stat-icon active">
              <CrownOutlined />
            </div>
          </div>
        </Card>
      </div>

      {/* 操作按钮和表格 */}
      <Card className="table-card">
        <div className="table-toolbar">
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新增角色
          </Button>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={actualDataSource}
          rowKey={(record) => record.roleId || record.id || record.key}
          loading={loading}
          pagination={{
            total: actualDataSource.length,
            current: 1,
            pageSize: 50,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新建/编辑角色弹窗 */}
      <Modal
        title={editingRole ? '编辑角色' : '新建角色'}
        open={isModalVisible}
        onOk={handleSave}
        onCancel={() => setIsModalVisible(false)}
        width={700}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            status: '启用',
            permissions: []
          }}
        >
          <Form.Item
            label="角色名称"
            name="roleName"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>

          <Form.Item
            label="角色描述"
            name="description"
            rules={[{ required: true, message: '请输入角色描述' }]}
          >
            <Input.TextArea rows={3} placeholder="请输入角色描述" />
          </Form.Item>

          <Form.Item
            label="权限配置"
            name="permissions"
            rules={[{ required: true, message: '请选择权限' }]}
          >
            <Tree
              checkable
              defaultExpandAll
              treeData={permissionTree}
              style={{ maxHeight: 300, overflow: 'auto', border: '1px solid #d9d9d9', borderRadius: 4, padding: 8 }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default PermissionManagement
